package ar.edu.itba.tp1.gps;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public class CalcuDokuEngine extends GPSEngine {

	@Override
	public void addNode(GPSNode node) {
		int index;

		switch (strategy) {
	        case BFS:
	                open.add(node);
	                break;
	        case DFS: case PI: case GS:
	                open.add(0,node);
	                break;
	        case AStar:
	        	index = Collections.binarySearch(open, node,
                        new Comparator<GPSNode>() {
                                public int compare(GPSNode o1, GPSNode o2) {
                                	int h1 = problem.getHValue(o1.getState());
                                	int h2 = problem.getHValue(o2.getState());

                                	int f1 = o1.getCost() + h1;
                                    int f2 = o2.getCost() + h2;
                                    
                                    if (f1 < f2) {
                                        return -1;
                                    } else if (f1 == f2) {
                                		if (h1 < h2) {
                                			return -1;
                                		} else if (h1 == h2) {
                                			return 0;
                                		}
                                    } 
                                    return 1;
                                }
                        });
	        	if (index >= 0) {
	        		open.add(index, node);
	        	} else {
	        		open.add(-1 * (index + 1), node);
	        	}
	        	break;
		}
		
		// --
		List<GPSNode> openList = openHash.get(node.getState());
        if(openList == null){
                openList = new LinkedList<GPSNode>();
                numberOfStates++;
                openHash.put(node.getState(), openList);
        }
        openList.add(node);
		// --
	}

}
